package p400;

public class Leetcode_498 {

    public int[] findDiagonalOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return new int[]{};
        }
        int r = 0, c = 0;
        int row = matrix.length, col = matrix[0].length;
        int[] res = new int[row * col];
        for (int i = 0; i < res.length; i++) {
            res[i] = matrix[r][c];
            // r+c为奇数，向上读取，为偶数，向下读取
            if ((r + c) % 2 == 0) {
                if (c == col - 1) {
                    // 到了最左边，向下移动一格
                    r++;
                } else if (r == 0) {
                    // 到了最上面，向右移动一格
                    c++;
                } else {
                    r--;
                    c++;
                }
            } else {
                if (r == row - 1) {
                    // 往右移动一格准备向上遍历
                    c++;
                } else if (c == 0) {
                    // 往下移动一格准备向上遍历
                    r++;
                } else {
                    // 往下移动
                    r++;
                    c--;
                }
            }
        }
        return res;
    }
}
